<?php
/**
 * Enter description here...
 *
 * @package if
 * @subpackage module.helper.controllers
 * @since 1.0
 */
class IfHelperModelController extends IHelperController {
	function _init() {
		//已经有的模型
		$models = f(IApplication::singleton()->directory("models"))->lists("*.php", true, true);
		$reged = array();
		foreach ($models as $file) {
			$name = $file->name();
			$model = substr($name, 0, strpos($name, "."));
			if (!in_array($model, $reged)) {
				$reged[] = $model;
			}
		}
		
		$this->models = $reged;
	}
	
	function doIndex() {
		
	}
	
	function doCreate() {
		try {
			$this->tables = IDb::driverByOpt()->tableList();
		} catch (IDbException  $e) {
			p($e->getMessage());
			exit("无法连接到数据库，请检查数据库配置");
		}
		
		//已经生成的表
		$gtables = array();
		foreach ($this->models as $model) {
			$gtables[] = IDAO::dao($model)->table();
		}
		$this->tables = array_diff($this->tables, $gtables);
		array_unshift($this->tables, "All");
		
		if ($this->form()->isValid()) {
			$index = intval(x("index"));
			if (isset($this->tables[$index])) {
				$tables = $this->tables;
				if ($index != 0) {
					$tables = array( $tables[$index] );
				}
				else {
					unset($tables[0]);
				}
				$prefix = x("prefix");
				foreach ($tables as $table) {
					$modelName = $prefix . ucfirst(if_name_to_java($table));
					$dirname = IApplication::singleton()->directory("models");
					$this->_createModel($dirname, $modelName, $table);
				}
			}
			
			$this->redirect("create");
		}
	}
	
	function doModel() {
		$model = x("model");
		$this->file = IVM::singleton()->findClass($model);
		$this->contents = file_get_contents($this->file);
		
		if ($this->request()->isPost()) {
			$source = rtrim(xn("source"));
			$this->contents = $source;
			file_put_contents($this->file, $source);
			if (x("save_and_refresh")) {
				echo "<script>window.parent.location.reload();</script>";
				return 1;
			}
		}
	}
	
	function doDelete() {
		unlink(x("file"));
		$this->redirect("index");
	}
	
	private function _createModel($dirname, $modelName, $table) {
		$file = f($dirname . "/" . $modelName . ".php");
		if ($file->exists()) {
			$this->log("skip {$modelName}, model already exists");
			return;
		}
		$class =  "<?php\n";
		$class .= "\n";
		$class .= "class {$modelName} extends IDbRecord {\n";
		$class .= "	static \$_table = \"{$table}\";\n";
		$class .= "\n";
		$class .= "}\n";
		$class .= "\n";
		$class .= "?>";

		$file->writer()->write($class);
		$this->log("created {$modelName}");
	}
}

?>